package cn.ltpcloud.admin.auth.service.impl;

import cn.ltpcloud.admin.auth.params.LoginParam;
import cn.ltpcloud.admin.auth.service.AuthService;
import cn.ltpcloud.common.constant.HttpStatus;
import cn.ltpcloud.common.entity.AjaxResult;
import cn.ltpcloud.common.pojo.auth.LoginUser;
import cn.ltpcloud.common.pojo.mapper.SysUserMapper;
import cn.ltpcloud.common.pojo.po.SysUser;
import cn.ltpcloud.common.utils.JWTUtils;
import cn.ltpcloud.common.utils.RedisUtils;
import cn.ltpcloud.common.utils.ReqUtils;
import com.baomidou.dynamic.datasource.annotation.Slave;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author jiejiebiezheyang
 * @since 2024-03-03 11:00
 */
@Service
@Transactional
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 登录
     */
    @Override
    public AjaxResult login(LoginParam loginParam) {
        // 使用authenticate进行认证
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(loginParam.getUsername(), loginParam.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        // 认证没通过,给出提示
        if (authenticate == null) {
            return AjaxResult.error(HttpStatus.LOGIN_ERROR);
        }
        Map<String, Object> map = new HashMap<>();
        // 认证通过
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        SysUser user = loginUser.getSysUser();
        user.setPassword(null);
        map.put("user_id", user.getId());
        map.put("nickname", user.getNickname());
        map.put("last_login", user.getLastLogin());
        map.put("last_login_ip", user.getLastLoginIp());
        // 更新登录记录
        user.setLastLoginIp(ReqUtils.getIP());
        user.setLastLogin(new Date());
        sysUserMapper.updateById(user);
        // 使用 userId 和 角色 生成token,返回token
        String userId = String.valueOf(loginUser.getSysUser().getId());
        String token = JWTUtils.createToken("userId", userId, 120 * 60);
        // 把用户信息存入redis
        redisUtils.setCacheObject("login:" + userId, loginUser, 120L * 60L, TimeUnit.SECONDS);
        // 返回token给前端
        map.put("token", token);
        return AjaxResult.success(map);
    }

    /**
     * 登录状态测试
     */
    @Override
    public AjaxResult ping() {
        return AjaxResult.success();
    }
}
